/* 
 * Copyright (C) 2010-2012 星星<349446658@qq.com>
 * 
 * This file is part of Wabacus 
 * 
 * Wabacus is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.wabacusdemo;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sun.jmx.snmp.SnmpUnknownSubSystemException;
import com.wabacus.config.Config;
import com.wabacus.config.component.IComponentConfigBean;
import com.wabacus.system.CacheDataBean;
import com.wabacus.system.ReportRequest;
import com.wabacus.system.assistant.WabacusAssistant;
import com.wabacus.system.serveraction.IServerAction;
import com.wabacus.util.Tools;
import com.wabacus.util.UUIDGenerator;

public class TestServerCallBack1 implements IServerAction
{
    /**
     * 与框架无关的ajax调用
     */
    public String executeServerAction(HttpServletRequest request,HttpServletResponse response,List<Map<String,String>> lstData)
    {
        System.out.println("11111111executeServerAction(HttpServletRequest request,HttpServletResponse response,List<Map<String,String>> lstData)方法...");
        printLstParams(lstData);//打印客户端传过来的参数
        if(lstData==null||lstData.size()==0) return "没有传入数据";
        Connection conn=Config.getInstance().getDataSource("").getConnection();//取配置的默认数据源的连接
        PreparedStatement pstmt=null;
        try
        {
            for(Map<String,String> mParams:lstData)
            {//将传入的每条数据插入数据库中
                String content=mParams.get("text");//从客户端取传过来的数据
                String updatetype=mParams.get("actiontype");//从客户端取传过来的数据
                if(updatetype==null||updatetype.trim().equals("")) continue;
                if(updatetype.equals("clear"))
                {//当前是做清空记录的操作
                    pstmt=conn.prepareStatement("delete from tbl_log");
                    pstmt.executeUpdate();
                    pstmt.close();
                    return "插入数据成功";
                }else
                {
                    if(content==null||content.trim().equals("")) continue;
                    pstmt=conn.prepareStatement("insert tbl_log(uuid,createdate,content,updatetype) values(?,?,?,?)");
                    pstmt.setString(1,UUIDGenerator.generateID());
                    pstmt.setTimestamp(2,new Timestamp((new Date()).getTime()));
                    pstmt.setString(3,content);
                    pstmt.setString(4,updatetype);
                    pstmt.executeUpdate();
                    pstmt.close();
                }
            }
            return "插入数据成功";
        }catch(Exception e)
        {
            e.printStackTrace();
            return "调用失败";
        }finally
        {
            WabacusAssistant.getInstance().release(conn,null);
        }
    }

    /**
     * 针对组件通过ajax调用服务器端方法
     */
    public String executeSeverAction(ReportRequest rrequest,IComponentConfigBean ccbean,List<Map<String,String>> lstData)
    {
    	SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS");
    	SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
    	String XTGSID="",BBRQ="",newBBWJLJ="",ID="";
    	int i=0;
    	for(Map<String,String> mParams:lstData)
        {
    		i++;
    		if(i==1){
    			ID=mParams.get("ID");
    			XTGSID= mParams.get("xtgsjc");
    			BBRQ= mParams.get("bbrq");
    		}
    		else if(!XTGSID.equalsIgnoreCase(mParams.get("xtgsjc"))){
    			 rrequest.getWResponse().getMessageCollector().error("所选择的第"+i+"条记录和第一条记录不是同一个公司的报表数据，不同公司的报表数据不能合并在一起",true);
    		}
    		else if(!BBRQ.equalsIgnoreCase(mParams.get("bbrq"))){
   				rrequest.getWResponse().getMessageCollector().error("所选择的第"+i+"条记录和第一条记录不是同一日期的报表数据，不同日期的报表数据不能合并在一起",true);
    		}
        }
    	i=0;
    	for(Map<String,String> mParams:lstData)
        {
    		i++;
    		String bbwjlj = mParams.get("bbwjlj");
    		bbwjlj=bbwjlj.substring(0, bbwjlj.lastIndexOf("."));
    		if(i==1){
    			newBBWJLJ=bbwjlj.substring(0, bbwjlj.lastIndexOf("/")+1)+format.format(new Date());
				try {
	    			File destFile = new File(newBBWJLJ);				
					File sourceFile = new File(bbwjlj);
					if(destFile.exists()&&destFile.isFile()){
						newBBWJLJ=newBBWJLJ+"_"+(Math.random()*1000);
						destFile = new File(newBBWJLJ);
					}
					if(!destFile.exists())destFile.mkdirs();
					Tools.copyDirectory(sourceFile,destFile);
				} catch (IOException e) {
					rrequest.getWResponse().getMessageCollector().error("所选择的第"+i+"条记录合并失败，请保证目标路径可写并且源文件存在并可读",true);
				}
    		}
    		else{
				try {
	    			File destFile = new File(newBBWJLJ);				
					File sourceFile = new File(bbwjlj);
					Tools.copyDirectory(sourceFile,destFile);
				} catch (IOException e) {
					rrequest.getWResponse().getMessageCollector().error("所选择的第"+i+"条记录合并失败，请检查所选记录的源文件是否存在",true);
				}
    		}
        }
        String bbwjlj2=newBBWJLJ.substring(newBBWJLJ.lastIndexOf("/")+1);
        String bbwjlj3=newBBWJLJ.substring(0, newBBWJLJ.lastIndexOf("/"));
        Tools.zipFolder(newBBWJLJ, bbwjlj3, bbwjlj2);
        Connection conn = rrequest.getConnection();
        PreparedStatement pstmt=null;
		Statement stmt=null;
        //下面从数据库中取到本报表当前显示的所有no中对应的省、市、县数据，并存放在mData中
        Map<String,String> mDataTmp=new HashMap<String,String>();
        try
        {
        	long XinTuoGongSiID=0,MoBanID=0;
        	stmt=conn.createStatement();
            ResultSet rs=stmt.executeQuery("select a.xtgsid,a.mbid from EastShangBao A where a.id ="+ID+"");
            if(rs.next())
            {
            	XinTuoGongSiID=rs.getLong("xtgsid");
            	MoBanID=rs.getLong("mbid");
            }
            rs.close();
        	pstmt=conn.prepareStatement("insert into EastShangBao(xtgsid,bbrq,mbid,bbwjlj,sbsj,sessionid,state) values(?,?,?,?,?,?,?)");
            pstmt.setLong(1,XinTuoGongSiID);
            pstmt.setDate(2, java.sql.Date.valueOf(BBRQ));
            pstmt.setLong(3,MoBanID);
            pstmt.setString(4,newBBWJLJ + ".zip");
            pstmt.setTimestamp(5,new Timestamp((new Date()).getTime()));
            pstmt.setString(6,rrequest.getRequest().getSession().getId());
            pstmt.setLong(7,1);
            pstmt.executeUpdate();
            pstmt.close();
        }catch(SQLException e){
        }finally{
            try
            {
            	if(stmt!=null){
            		stmt.close();
            	}
            	if(pstmt!=null){
            		pstmt.close();
            	}
            }
            catch(SQLException e)
            {
            }
        }
        rrequest.getWResponse().getMessageCollector().success("合并成功",false);//向前台提示一条信息，这里还可以终止后续处理
        return "";
    }

    private void printLstParams(List<Map<String,String>> lstData)
    {
        if(lstData==null||lstData.size()==0)
        {
            System.out.println("无参数");
        }else
        {
            System.out.print("客户端传入参数列表：：：");
            for(Map<String,String> mParams:lstData)
            {
                StringBuffer paramBuf=new StringBuffer();
                for(Entry<String,String> entryTmp:mParams.entrySet())
                {
                    paramBuf.append("[paramname:"+entryTmp.getKey()+";paramvalue:"+entryTmp.getValue()+"]");
                }
                System.out.print("{"+paramBuf.toString()+"};");
            }
            System.out.println(" ");
        }
    }
    

}

